package com.feng.gulimall.product.service.impl;

import com.alibaba.nacos.api.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.feng.gulimall.product.entity.CategoryBrandRelationEntity;
import com.feng.gulimall.product.service.CategoryBrandRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feng.common.utils.PageUtils;
import com.feng.common.utils.Query;

import com.feng.gulimall.product.dao.BrandDao;
import com.feng.gulimall.product.entity.BrandEntity;
import com.feng.gulimall.product.service.BrandService;
import org.springframework.transaction.annotation.Transactional;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String) params.get("key");
        LambdaQueryWrapper<BrandEntity> wrapper = new LambdaQueryWrapper<>();
        if (key != null && !"".equals(key)){
            wrapper.eq(BrandEntity::getBrandId, key).or()
                    .eq(BrandEntity::getFirstLetter, key).or()
                    .like(BrandEntity::getName, key).or();
        }
        wrapper.orderByAsc(BrandEntity::getSort);

        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Transactional   // 添加事务
    @Override
    public void updateDetal(BrandEntity brand) {
        // 先更新当前表
        baseMapper.updateById(brand);
        // 如果更改了名称
        if (!StringUtils.isBlank(brand.getName())){
            categoryBrandRelationService.updateBrandName(brand.getBrandId(), brand.getName());

            //TODO 更新其他关联
        }
    }

}
